﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DailyComics.Common.Utilities
{
  public class SizeRestrictedCache<TKey, TValue> : Cache<TKey, TValue>
  {
    private int counter;
    private Dictionary<int, TKey> expirationDictionary;

    public int Size { get; private set; }

    public SizeRestrictedCache(int size)
    {
      this.Size = size;
      this.counter = 0;
      this.expirationDictionary = new Dictionary<int, TKey>();
    }

    public override void Add(TKey key, TValue value)
    {
      if (ContainsKey(key)) return;

      if (dictionary.Count == Size)
      {
        dictionary.Remove(expirationDictionary[expirationDictionary.Min(k => k.Key)]);
        expirationDictionary.Remove(expirationDictionary.Min(k => k.Key));
      }

      expirationDictionary.Add(counter++, key);
      
      base.Add(key, value);
    }
  }
}
